<style scoped lang="less">
  @import "store-info.less";
</style>
<template>
  <Card>
    <Form ref="myForm" :model="formItem" :rules="ruleValidate" :label-width="80">
	    <FormItem label="店铺标签">
		    <Select :disabled="showOnly" v-model="formItem.tag" style="width:100px">
			    <Option :value="-1">不选</Option>
			    <template v-for="item in tags" >
				    <Option class="tag-wrap" :value="item.id">{{item.title}}<img class="tag-icon" :src="GLOBAL.getUrl(item.icon[0],false,true)"/></Option>
			    </template>
		    </Select>
	    </FormItem>
      <FormItem label="店铺名" prop="name">
        <Input v-model="formItem.name" placeholder="请输入店铺名" :readonly="showOnly" style="width: 200px;"></Input>
      </FormItem>
      <FormItem label="联系电话" prop="phone">
        <Input v-model="formItem.phone" placeholder="请输入联系电话" :readonly="showOnly" style="width: 200px;"></Input>
      </FormItem>
      <FormItem label="地址" prop="address">
        <Input v-model="formItem.address" placeholder="地址" :readonly="showOnly" style="width: 400px;"></Input>
      </FormItem>
      <FormItem label="营业时间" prop="business_time">
	      <TimePicker v-model="formItem.business_time" format="HH:mm" type="timerange" placement="bottom-end" placeholder="请选择营业时间" style="width: 150px"></TimePicker>
      </FormItem>
      <div id="store-info-container"></div>
      <div id='store-info-right'>
        <div>
          <div class='title'>提示（此地址仅供参考）</div>
          <div class='c'>地址:</div>
          <div id='address'></div>
        </div>
      </div>
      <FormItem label="营业执照" prop="no">
        <Input v-model="formItem.no" placeholder="营业执照编号" :readonly="showOnly" style="width: 200px;"></Input>
      </FormItem>
      <FormItem label="营业执照照片" prop="no_img">
        <SelectImg v-model="formItem.no_img" @on-selected-imgs="noImgSelected" :canOp="!showOnly"
                   :limit="1"
                   :initList="formItem.no_img"></SelectImg>

      </FormItem>
      <FormItem label="省市区(县)" prop="region">
        <AreaCascader :type="'code'"  v-model="formItem.region" level="2" :disabled="showOnly" style="width:350px"/>
      </FormItem>
      <FormItem label="店铺照片" prop="imgs">
        <SelectImg v-model="formItem.store_img" @on-selected-imgs="storeImgSelected" :canOp="!showOnly"
                   :limit="9"
                   :initList="formItem.store_img"></SelectImg>
      </FormItem>
    </Form>
    <div class="store-info-btn-wrap" v-if="!showOnly">
      <Button type="primary" @click="submit" :loading="loading">确定</Button>
    </div>
  </Card>
</template>
<script>

  import {get, save, del, edit} from '@/api/stores'
  import {getList} from '@/api/store-tag'
  import SelectImg from '../../components/select-img'
  import AreaCascader from '../../components/area'
  export default{
    name: 'store-info',
    components: {
      SelectImg,
      AreaCascader
    },
    mounted(){
      this.getTags();
      this.init();
    },
    watch: {
      // 监听相同路由下参数变化的时候，从而实现异步刷新
      '$route' (to, from) {
        // 重置数据
        Object.assign(this.$data, this.$options.data());
        /** 初始化其他数据 */
        this.init();
      }
    },

    data(){
      return {
        showOnly: false,
        loading: false,
	      tags:[],
        formItem: {
          tag:-1,
          id: -1,
          name: '',
          phone: '',
          address: '',
          no: '',
          business_time: [],
          no_img: [],
          store_img: [],
          ln: '',
          la: '',
          region: []
        },
        ruleValidate: {
          name: [
            {required: true, message: '店名不能为空', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '手机号不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                if (!value) {
                  callBack('请输入手机号码');
                } else if (/^[1][0-9]{10}$/.test(value)) {
                  callBack();
                } else {
                  callBack('请输入正确的手机号码');
                }
              }
            }
          ],
          address: [
            {required: true, message: '地址不能为空', trigger: 'blur'}
          ],
          no: [
            {required: true, message: '营业执照编号不能为空', trigger: 'blur'}
          ],
          no_img: [
            {required: true, type: 'array', message: '请上传营业执照图片', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  callback('请上传营业执照图片');
                } else if (value.length === 0 || value[0] === '') {
                  callback('请上传营业执照图片');
                } else {
                  callback();
                }
              }
            }
          ],
          business_time: [
            {required: true, type: 'array', message: '请选择时间', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  callback('请选择时间');
                } else if (value.length === 0 || value[0] === '') {
                  callback('请选择时间');
                } else {
                  callback();
                }
              }
            }
          ],
          store_img: [
            {required: true, type: 'array', message: '请上传店铺图片', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  callback('请上传店铺图片');
                } else if (value.length === 0 || value[0] === '') {
                  callback('请上传店铺图片');
                } else {
                  callback();
                }
              }
            }
          ],
          region: [
            {required: true, type: 'array', message: '请选择地区', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  callback('请选择地区');
                } else if (value.length < 3) {
                  callback('请选择地区');
                } else {
                  callback();
                }
              }
            }
          ],
          ln: [
            {required: true, message: '请选择定位', trigger: 'blur'}
          ],
          la: [
            {required: true, message: '请选择定位', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      init(){
        this.showOnly = false;
        this.formItem.id = -1;
        let id = this.$route.params.id;
        let view = this.$route.params.view;
        if (id !== undefined) {
          this.formItem.id = id;
          if (view !== undefined &&view!=0) {
            this.showOnly = true;
          }
          this.getData();
        }else {
          this.mapInit()
        }
      },
      storeImgSelected(img){
        this.formItem.store_img = img;
      },
      noImgSelected(img){
        this.formItem.no_img = img;
      },
      getTags() {
        let vm = this;
        getList().then(response => {
          response.data.data.forEach(v => {
            v.icon = JSON.parse(v.icon);
          });
          vm.tags = response.data.data;
        })
      },
      mapInit () {
        let that = this;
        let mapContainerConfig = {zoom: 16};
        if (that.formItem.ln !== '' && that.formItem.ln !== undefined && that.formItem.la !== '' && that.formItem.la !== undefined) {
          mapContainerConfig.center = [that.formItem.ln, that.formItem.la];
        }
        AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {
          var map = new AMap.Map('store-info-container', mapContainerConfig);
          var positionPicker = new PositionPicker({
            mode: 'dragMap',
            map: map
          });
          AMap.plugin(['AMap.ToolBar'], function () {
            map.addControl(new AMap.ToolBar({
              map: map
            }));
          });
          positionPicker.on('success', function (positionResult) {
            that.formItem.ln = positionResult.position.lng;
            that.formItem.la = positionResult.position.lat;
            document.getElementById('address').innerHTML = positionResult.address;
          });
          positionPicker.on('fail', function (positionResult) {
            document.getElementById('lnglat').innerHTML = ' ';
            document.getElementById('address').innerHTML = ' ';
          });

          positionPicker.start();
          map.panBy(0, 1);
        });
      },
      getData(){
        let vm = this;
          get(vm.formItem.id).then(rep =>{
            vm.setInfo(rep.data.data);
            vm.mapInit();
          },error=>{})
      },
      setInfo(data){
        let vm = this;
        vm.formItem.id = data.id;
        vm.formItem.tag = data.tag;
        vm.formItem.name = data.name;
        vm.formItem.phone = data.phone;
        vm.formItem.address = data.address;
        vm.formItem.business_time = [data.business_start,data.business_end];
        vm.formItem.no = data.no;
        vm.formItem.no_img = JSON.parse(data.no_img);
        vm.formItem.store_img = JSON.parse(data.store_img);
        vm.formItem.ln = data.ln;
        vm.formItem.la = data.la;
        vm.formItem.region = [];
        if(data.province!==null){
          vm.formItem.region.push(data.province);
          if(data.city!==null){
            vm.formItem.region.push(data.city);
            if(data.district!==null){
              vm.formItem.region.push(data.district);
            }
          }
        }
      },
      submit () {
        let self = this;
        this.$refs['myForm'].validate((valid) => {
          if (valid) {
            self.loading = true;
            let target = '';

            let params = {};
            if (self.formItem.id !== -1) {
              params.id = self.formItem.id;
            }

            params.name = self.formItem.name;
            params.tag = self.formItem.tag;
            params.uid = self.formItem.uid;
            params.phone = self.formItem.phone;
            params.address = self.formItem.address;
            params.business_start = self.formItem.business_time[0];
            params.business_end = self.formItem.business_time[1];
            params.no = self.formItem.no;
            params.no_img = JSON.stringify(self.formItem.no_img);
            params.store_img = JSON.stringify(self.formItem.store_img);
            params.province = self.formItem.region[0].code;
            params.city = self.formItem.region[1].code;
            params.district = self.formItem.region[2].code;
            params.ln = self.formItem.ln;
            params.la = self.formItem.la;
            if (self.formItem.id !== -1) {
              params.id = self.formItem.id;
              edit(params).then(response => {
                self.$Message.success(response.data.msg);
                self.showOnly = true;
              }, (error) => {});
            }else {
              save(params).then(response => {
                self.$Message.success(response.data.msg);
                self.formItem.id = response.data.data;
                self.showOnly = true;
              }, (error) => {});

            }

          }
        });
      },
    }
  }
</script>
